package Num_frac;

use Moose;
use Inline 'C';

##### Copia del constructor
### De la parte de la practica Cosntructor solución, 
## este es un constructor que comple los requerimeintos de polimorfismo

has den

has num

{
my $isint = qr {^\s*-?\d+\s*$};
my $isfrac = qr {^\s*(-?\d+)(\(-?\d+))?$};

	sub new { 
	my $class = shift;
	my $self; 
	if (@_ >= 2){
		return unless $_[0] =~ $isint and $_[1] =~ $isint;
		$self->{num} = $_[0]; 
		unless ($_[1]) {
			carp "Can't make a $class with denominator 0";
			return;
			}
		$self->{den} = $_[1]; 
	}
	elsif (@_ == 1) {
		if (ref $_[0]) { #Number::Fraction->new($x) y $x objetivo. Lo copiamos
			return $class->new ($_[0]->{num}, $_[0]->{den}) if (UNIVERSAL::isa($_[0], __PACKAGE__));
			croak "Can’t make a $class from a ", ref $_[0];
			}
			else { # Es una cadena 'num/num' o 'num'
			return unless $_[0] =~$isfrac;
			$self->{num}= $1;
			$self->{den} = $3 || 1;
			}
		}
		elsif (ref($class)) {	# Llamado $x->new. Copiamos el objeto
			%$self = %$class;
		}
		else {
			$self->{num}= 0;
			$self->{den} = 1;
		}
		bless $self, $class; 
		$self->normalise; 
		return $self; 
	}
}

####Copia de la normalización

sub normalise {
	my $self = shift;
	
	#calculamos el max coumn divisor hcf
	my $hcf = _hcf($self->{num}, $self->{den});
	
	# y dividimos ambos por el hcf
	#for (qw/num den/) { $self->{$_} /= $hcf;}
	$self->{num} /= $hcf;
	$self->{den} /= $hcf;

	#Denominador positivo en forma normalizada
	if ($self->{den} < 0) { 
		$self->{num} *= -1;
		$self->{den} *= -1;
	#for (qw/num den/) {$self->{$_} *= -1;}
	}
}

######Copia del max comun divisor (HCF)

sub _hcf { 
	my ($x, $y) = @_; 
	($x, $y) = ($y, $x) if $y > $x; 
	return $x if $x == $y;
	while ($y) {
		($x, $y) = ($y, $x % $y); 
		}
		return $x;
}

our $VERSION = '0.01';


# Preloaded methods go here.

1;
__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

Num_frac - Perl extension for blah blah blah

=head1 SYNOPSIS

  use Num_frac;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for Num_frac, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.

=head2 EXPORT

None by default.



=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

Leticia Gonzalez, E<lt>leticiagonzalez@apple.comE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2011 by Leticia Gonzalez

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.


=cut
